<template>
  <div class="card-content-wrapper">
    <div v-if="item?.data?.content?.type === 'video'" class="video-container" @click="handleVideoClick">
      <video ref="videoPlayerRef" :src="videoPlayUrl" loop
        :poster="item?.data?.content?.data?.cover?.detail || item?.data?.content?.data?.cover?.feed"
        class="video-player" autoplay muted playsinline @play="handleVideoPlay" @pause="handleVideoPause"
        @loadedmetadata="handleVideoLoaded"></video>
      <div v-if="showPlayIcon" class="play-icon-overlay">
        <van-icon name="play" class="play-icon-large" />
      </div>
    </div>

    <div v-else-if="item?.data?.content?.type === 'ugcPicture'" class="photos-container">
      <van-swipe :loop="false" :show-indicators="photosCount > 1" :initial-swipe="currentPhotoIndex"
        @change="handlePhotoChange" class="photos-swipe">
        <van-swipe-item v-for="(url, index) in photoUrls" :key="index">
          <img :src="url" class="photo-image" />
        </van-swipe-item>
      </van-swipe>
      <div v-if="photosCount > 1" class="photo-count">
        {{ currentPhotoIndex + 1 }} / {{ photosCount }}
      </div>
    </div>

    <div class="header-controls" :class="{ hidden: !showInfo }">
      <div class="pull-down-btn" @click.stop="handleClose">
        <van-icon name="arrow-down" class="pull-down-icon" />
      </div>
    </div>

    <div class="info-bar" :class="{ hidden: !showInfo }" @click.stop>
      <div class="user-info">
        <div class="avatar-wrapper">
          <img :src="item?.data?.content?.data?.owner?.avatar || ''" class="avatar"
            :class="{ 'round-avatar': isRoundAvatar }" />
          <van-icon v-if="isExpert" name="star" class="avatar-star" />
        </div>
        <div class="user-name">{{ item?.data?.content?.data?.owner?.nickname || '未知用户' }}</div>
        <div class="user-actions">
          <van-button size="small" type="primary" plain class="private-letter-btn" @click.stop="handlePrivateLetter">
            私信
          </van-button>
          <van-button size="small" type="default" class="follow-btn" @click.stop="handleFollow">
            关注
          </van-button>
        </div>
      </div>

      <div v-if="description" class="description">{{ description }}</div>

      <div v-if="tagName" class="tag">{{ tagName }}</div>

      <div class="divider"></div>

      <div class="action-bar">
        <div class="action-item" @click.stop="handleCollection" :class="{ 'liked': isLiked }">
          <van-icon :name="isLiked ? 'like' : 'like-o'" class="action-icon" />
          <span class="action-text">{{ displayCollectionCount }}</span>
        </div>
        <div class="action-item" @click.stop="handleReply">
          <van-icon name="chat-o" class="action-icon" />
          <span class="action-text">{{ replyCount }}</span>
        </div>
        <div class="action-item" @click.stop="handleFavorites" :class="{ 'favorited': isFavorited }">
          <van-icon :name="isFavorited ? 'star' : 'star-o'" class="action-icon" />
          <span class="action-text">{{ displayFavoriteCount }}</span>
        </div>
        <div class="action-spacer"></div>
        <div class="action-item" @click.stop="handleShare">
          <van-icon name="share-o" class="action-icon share-icon" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue';
import { showToast } from 'vant';
import { useFavoritesStore } from '@/stores/favorites';

interface Props {
  item: any; // 卡片数据
  showInfo?: boolean; // 是否显示底部信息栏
}

const props = withDefaults(defineProps<Props>(), {
  item: null,
  showInfo: true
});

const emit = defineEmits<{
  'video-play': [];
  'video-pause': [];
  'photo-change': [index: number];
  'toggle-info': [];
  'close': [];
  'private-letter': [];
  'follow': [];
  'collection': [];
  'reply': [];
  'favorites': [];
  'share': [];
}>();

const favoritesStore = useFavoritesStore();

// 点赞状态
const isLiked = ref(false);
const likeCountIncrement = ref(0);

// 收藏数字增量
const favoriteCountIncrement = ref(0);

// DOM引用
const videoPlayerRef = ref<HTMLVideoElement | null>(null); // 视频播放器DOM引用

// 图片轮播状态
const currentPhotoIndex = ref(0); // 当前显示的图片索引

// 视频播放状态
const isVideoPlaying = ref(false); // 视频是否正在播放
const showPlayIcon = ref(false); // 是否显示播放图标
let playIconTimer: number | null = null; // 播放图标显示定时器

// 计算属性
const videoPlayUrl = computed(() => {
  // 获取视频播放地址
  const data = props.item?.data?.content?.data;
  if (!data) return '';
  return data.playUrl || data.playInfo?.url || data.url || '';
});

const photoUrls = computed(() => {
  // 获取图片URL数组
  return props.item?.data?.content?.data?.urls || [];
});

const photosCount = computed(() => {
  // 获取图片数量
  return photoUrls.value.length;
});

const description = computed(() => {
  // 获取描述文本
  return props.item?.data?.content?.data?.description || '';
});

const tagName = computed(() => {
  // 获取第一个标签名称
  const tags = props.item?.data?.content?.data?.tags;
  return tags && tags.length > 0 ? tags[0]?.name : '';
});

const collectionCount = computed(() => {
  // 获取收藏数
  return props.item?.data?.content?.data?.consumption?.collectionCount || 0;
});

// 显示的点赞数（原始值 + 增量）
const displayCollectionCount = computed(() => {
  return collectionCount.value + likeCountIncrement.value;
});

const replyCount = computed(() => {
  // 获取评论数
  return props.item?.data?.content?.data?.consumption?.replyCount || 0;
});

// 显示的收藏数（原始值 + 增量）
const displayFavoriteCount = computed(() => {
  const baseCount = props.item?.data?.content?.data?.consumption?.realCollectionCount || 0;
  return baseCount + favoriteCountIncrement.value;
});

const isExpert = computed(() => {
  // 判断是否为专家用户
  return props.item?.data?.content?.data?.owner?.expert || false;
});

// 检查是否已收藏
const isFavorited = computed(() => {
  const data = props.item?.data?.content?.data;
  if (!data?.id) return false;
  return favoritesStore.isFavorited(data.id);
});

const isRoundAvatar = computed(() => {
  // 判断头像是否为圆形
  return props.item?.data?.header?.iconType === 'round';
});

// 处理视频播放事件
const handleVideoPlay = () => {
  isVideoPlaying.value = true;
  showPlayIcon.value = false;
  if (playIconTimer) {
    clearTimeout(playIconTimer);
    playIconTimer = null;
  }
  emit('video-play');
};

// 处理视频暂停事件
const handleVideoPause = () => {
  isVideoPlaying.value = false;
  emit('video-pause');
};

// 自动播放视频的函数
const autoPlayVideo = async () => {
  await nextTick();
  if (videoPlayerRef.value && props.item?.data?.content?.type === 'video') {
    try {
      // 先暂停所有其他视频
      const allVideos = document.querySelectorAll('video');
      allVideos.forEach((video) => {
        if (video !== videoPlayerRef.value) {
          video.pause();
        }
      });

      // 设置当前视频为静音并播放
      videoPlayerRef.value.muted = true;
      await videoPlayerRef.value.play();
      isVideoPlaying.value = true;
      showPlayIcon.value = false;
    } catch (error) {
      console.error('自动播放失败:', error);
      isVideoPlaying.value = false;
    }
  }
};

// 处理视频加载完成事件
const handleVideoLoaded = async () => {
  await autoPlayVideo();
};

// 处理视频点击事件：切换播放/暂停
const handleVideoClick = (e: MouseEvent) => {
  // 阻止事件冒泡，避免触发其他点击事件
  e.stopPropagation();

  if (!videoPlayerRef.value) return;

  if (isVideoPlaying.value) {
    // 如果正在播放，则暂停
    videoPlayerRef.value.pause();
    showPlayIcon.value = true;
    // 3秒后自动隐藏播放图标
    if (playIconTimer) {
      clearTimeout(playIconTimer);
    }
    playIconTimer = window.setTimeout(() => {
      showPlayIcon.value = false;
    }, 3000);
  } else {
    // 如果暂停，则播放
    videoPlayerRef.value.play();
    showPlayIcon.value = false;
    if (playIconTimer) {
      clearTimeout(playIconTimer);
      playIconTimer = null;
    }
  }
};

// 处理图片切换事件：更新当前图片索引
const handlePhotoChange = (index: number) => {
  currentPhotoIndex.value = index;
  emit('photo-change', index);
};

// 处理关闭事件
const handleClose = () => {
  emit('close');
};

// 处理私信点击：显示提示并触发事件
const handlePrivateLetter = () => {
  showToast('私信功能需要登录');
  emit('private-letter');
};

// 处理关注点击：显示提示并触发事件
const handleFollow = () => {
  showToast('关注功能需要登录');
  emit('follow');
};

// 处理点赞点击
const handleCollection = () => {
  if (!props.item?.data?.content?.data) return;

  if (!isLiked.value) {
    // 点赞：数字加一
    isLiked.value = true;
    likeCountIncrement.value = 1;
  } else {
    // 取消点赞：数字减一
    isLiked.value = false;
    likeCountIncrement.value = 0;
  }
  emit('collection');
};

// 处理评论点击：显示提示并触发事件
const handleReply = () => {
  showToast('评论功能暂不支持');
  emit('reply');
};

// 处理收藏点击：收藏/取消收藏
const handleFavorites = () => {
  const data = props.item?.data?.content?.data;
  if (!data) {
    emit('favorites');
    return;
  }

  // 检查登录状态
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
  if (!isLoggedIn) {
    showToast('请先登录');
    emit('favorites');
    return;
  }

  // 构建视频对象（兼容社区内容的数据结构）
  const video = {
    id: data.id,
    title: data.title || data.description || '未命名',
    description: data.description,
    playUrl: data.playUrl || data.playInfo?.url || data.url,
    cover: data.cover || data.coverInfo,
    author: {
      name: data.owner?.nickname || data.owner?.name || '未知',
      icon: data.owner?.avatar || data.owner?.icon
    },
    duration: data.duration,
    tags: data.tags,
    consumption: data.consumption
  };

  const wasFavorited = isFavorited.value;
  const success = favoritesStore.toggleFavorite(video);
  if (success) {
    if (!wasFavorited) {
      // 刚收藏，数字加一
      favoriteCountIncrement.value += 1;
      showToast('已收藏');
    } else {
      // 取消收藏，数字减一
      favoriteCountIncrement.value = Math.max(0, favoriteCountIncrement.value - 1);
      showToast('已取消收藏');
    }
  }
  emit('favorites');
};

// 处理分享点击：复制分享链接到剪贴板
const handleShare = () => {
  const item = props.item;
  if (!item) return;

  const data = item.data?.content?.data;
  if (!data) return;

  // 构建分享链接和文本
  const linkUrl = `https://www.eyepetizer.net/detail.html?vid=${data.id}&utm_campaign=routine&utm_medium=share&utm_source=others&uid=0&resourceType=${data.resourceType}`;
  const shareText = `${data.owner?.nickname} 在开眼发表了作品：\n「${data.description}」\n${linkUrl}`;

  // 使用 Clipboard API 或兼容方法复制到剪贴板
  if (navigator.clipboard) {
    navigator.clipboard.writeText(shareText).then(() => {
      showToast('分享链接已复制到剪贴板');
    });
  } else {
    // 兼容旧浏览器：使用 textarea 方式复制
    const textarea = document.createElement('textarea');
    textarea.value = shareText;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
    showToast('分享链接已复制到剪贴板');
  }
  emit('share');
};

// 监听 item 变化，切换卡片时自动播放视频
watch(() => props.item, (newItem) => {
  if (newItem?.data?.content?.type === 'video') {
    autoPlayVideo();
  } else {
    // 如果不是视频，确保视频暂停
    if (videoPlayerRef.value) {
      videoPlayerRef.value.pause();
      isVideoPlaying.value = false;
    }
  }
}, { deep: true, immediate: true });

// 监听视频 URL 变化，自动播放
watch(() => videoPlayUrl.value, (newUrl) => {
  if (newUrl && props.item?.data?.content?.type === 'video') {
    autoPlayVideo();
  }
});

defineExpose({
  videoPlayerRef
});
</script>

<style scoped lang="less">
.card-content-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #000;
}

.video-container {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;

  .video-player {
    width: 100%;
    height: 100%;
    object-fit: contain;
    background-color: #000;
    outline: none;
    border: none;

    &::-webkit-media-controls {
      display: none !important;
    }

    &::-webkit-media-controls-enclosure {
      display: none !important;
    }

    &::-webkit-media-controls-panel {
      display: none !important;
    }

    &::-webkit-media-controls-play-button {
      display: none !important;
    }

    &::-webkit-media-controls-start-playback-button {
      display: none !important;
    }
  }

  .play-icon-overlay {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 5;
    pointer-events: none;
    display: flex;
    align-items: center;
    justify-content: center;

    .play-icon-large {
      font-size: 60px;
      color: rgba(255, 255, 255, 0.9);
      background-color: rgba(0, 0, 0, 0.5);
      border-radius: 50%;
      padding: 20px;
      box-sizing: border-box;
    }
  }
}

.photos-container {
  width: 100%;
  height: 100%;
  position: relative;

  .photos-swipe {
    width: 100%;
    height: 100%;

    .photo-image {
      width: 100%;
      height: 100%;
      object-fit: contain;
      background-color: #000;
    }
  }

  .photo-count {
    position: absolute;
    top: 20%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 11px;
    pointer-events: none;
  }
}

.header-controls {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  padding: 12px 14px;
  box-sizing: border-box;
  z-index: 10;
  transition: opacity 0.3s ease;

  &.hidden {
    opacity: 0;
    pointer-events: none;
  }

  .pull-down-btn {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background-color: rgba(222, 222, 222, 0.9);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    .pull-down-icon {
      font-size: 16px;
      color: #333;
    }
  }
}

.info-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.5));
  padding: 13px 14px 0;
  box-sizing: border-box;
  transition: opacity 0.3s ease, transform 0.3s ease;

  &.hidden {
    opacity: 0;
    transform: translateY(100%);
    pointer-events: none;
  }
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;

  .avatar-wrapper {
    position: relative;
    width: 40px;
    height: 40px;
    margin-right: 6px;

    .avatar {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      object-fit: cover;

      &.round-avatar {
        border-radius: 50%;
      }
    }

    .avatar-star {
      position: absolute;
      bottom: 0;
      right: 0;
      width: 10px;
      height: 10px;
      background-color: #1989fa;
      border-radius: 50%;
      border: 1px solid #999;
      color: #fff;
      font-size: 6px;
      padding: 1px;
      box-sizing: border-box;
    }
  }

  .user-name {
    flex: 1;
    font-size: 14px;
    color: #fff;
    font-weight: 500;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right: 13px;
  }

  .user-actions {
    display: flex;
    gap: 13px;
    align-items: center;

    .private-letter-btn {
      height: 22px;
      padding: 0 8px;
      font-size: 10px;
      background-color: #1989fa;
      border-color: #1989fa;
      color: #fff;
    }

    .follow-btn {
      height: 22px;
      padding: 0 8px;
      font-size: 10px;
      background-color: rgba(255, 255, 255, 0.2);
      border-color: rgba(255, 255, 255, 0.3);
      color: #fff;
    }
  }
}

.description {
  font-size: 13px;
  color: #fff;
  line-height: 1.5;
  margin-top: 10px;
  padding: 0;
}

.tag {
  display: inline-block;
  font-size: 12px;
  color: #fff;
  background-color: rgba(127, 127, 127, 0.5);
  padding: 2px 5px;
  border-radius: 4px;
  margin-top: 10px;
  margin-left: 1px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 80%;
}

.divider {
  width: 100%;
  height: 1px;
  background-color: rgba(127, 127, 127, 0.5);
  margin-top: 14px;
}

.action-bar {
  display: flex;
  align-items: center;
  height: 51px;
  padding: 0;

  .action-item {
    display: flex;
    align-items: center;
    gap: 9px;
    cursor: pointer;
    padding: 0;
    margin-right: 20px;

    &.favorited {
      .action-icon {
        color: #ffd700;
      }
    }

    &.liked {
      .action-icon {
        color: #ff6b6b;
      }
    }

    .action-icon {
      font-size: 20px;
      color: #fff;
    }

    .share-icon {
      font-size: 20px;
      padding: 15px;
    }

    .action-text {
      font-size: 13px;
      color: #fff;
      font-weight: 500;
    }

    &:last-child {
      margin-right: 0;
    }
  }

  .action-spacer {
    flex: 1;
  }
}
</style>
